import { InputNumberProps, InputNumber } from 'antd';
import { FC, useContext, useEffect, useState } from 'react';
import { xhrGet } from '@/services';
import { useForm } from '@formily/react';
import { onFieldReact } from '@formily/core';
import { toArray } from '@/biz-components/_common/util';
import GlobalContext from '@/context';

interface CurrencyNumberProps extends InputNumberProps {
  deps?: string[]; // 依赖其他货币字段
  editable?: boolean; // 是否编辑
  defaultCurrency?: string; // 默认货币值
}

const CurrencyNumber: FC<CurrencyNumberProps> = ({
  deps,
  editable,
  value,
  defaultCurrency,
  ...restProps
}) => {
  const { dictionary } = useContext(GlobalContext) || {};
  const { CURRENCY_SYMBOL } = dictionary || {};

  const [currencySymbolList, setCurrencySymbolList] = useState(CURRENCY_SYMBOL || []);
  const [currencySymbol, setCurrencySymbol] = useState('');

  const [currency, setCurrency] = useState('');

  const form = useForm();

  const currencyField = toArray(deps)[0];

  const currencyValue = currencyField ? form.getValuesIn(currencyField) : defaultCurrency;

  const currencyFormatter = (val?: number | undefined | string) => {
    if (!val) return '';
    const d = (val).toString().split('.')
    const d1 = d[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    const d2 = d.length === 2 ? `.${d[1]}` : '';
    return `${currencySymbol || ''} ${d1}${d2}`;
  };

  const currencyParser = (val: string | undefined) => {
    if (!val) return `${currencySymbol} 0`;

    const reg = currencySymbol
      ? new RegExp(`\\${currencySymbol}\\s?|(,*)`, 'g')
      : new RegExp(`,`, 'g');

    return val.replace(reg, '');
  };

  const fetchCurrencySymbol = () => {
    xhrGet('/sym/dict/findValues', { code: 'CURRENCY_SYMBOL' }).then((res: any) => {
      const { result } = res;
      setCurrencySymbolList(result);
    });
  };

  useEffect(() => {
    if (CURRENCY_SYMBOL?.length) {
      return;
    }

    if (currencyField || defaultCurrency) {
      fetchCurrencySymbol();
    }
  }, [currencyField, defaultCurrency, CURRENCY_SYMBOL]);

  useEffect(() => {
    if (!currencyField) return;

    form.addEffects('current', () => {
      onFieldReact(currencyField, (field: any) => {
        setCurrency(field.value);
      });
    });

    return () => {
      form.removeEffects('current');
    };
  }, [form, currencyField, value]);

  useEffect(() => {
    setCurrency(currencyValue);
  }, [currencyValue]);

  useEffect(() => {
    const { name } = currencySymbolList.find((item: any) => item.code === currency) || { name: '' };
    setCurrencySymbol(name);
  }, [currencySymbolList, currency]);

  const renderDetail = () => {
    if (value) {
      return <span>{currencyFormatter(value)}</span>;
    }
    return <span>{`${currencySymbol} 0`}</span>;
  };

  const renderEdit = () => {
    return (
      <InputNumber
          style={{textAlign: 'right'}}
        {...restProps}
        value={value}
        formatter={(val) => {
          return val ? currencyFormatter(val) : '';
        }}
        parser={(val) => {
          return currencyParser(val);
        }}
        key={`currencySymbol_${currencySymbol}`}
      />
    );
  };

  return editable ? renderEdit() : renderDetail();
};

export default CurrencyNumber;
